package com.archive.controller;

import com.archive.common.*;
import com.archive.consts.CheckStatusEnum;
import com.archive.dto.PageDTO;
import com.archive.entity.TeachPaper;
import com.archive.entity.SysFile;
import com.archive.entity.SysUser;
import com.archive.service.TeachPaperService;
import com.archive.service.SysFileService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 教研论文表 前端控制器
 * </p>
 *
 * @author Janus
 * @since 2024-03-17
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/teach-paper")
public class TeachPaperController {

    private final TeachPaperService papeInfoService;
    private final SysFileService fileService;

    /**
     * 分页列表查询
     * @param queryParam 查询参数
     * @return
     */
    @ApiOperation(value = "分页列表")
    @RequestMapping(value = "/list",method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean getList(PageDTO pageDTO, TeachPaper queryParam, HttpSession session) {
        SysUser user = (SysUser) session.getAttribute("user");
        if(user == null){
            return ResultUtil.error("登录过期，请重新登录！");
        }
        log.debug("查询列表参数："+queryParam+",pageDTO:"+pageDTO);
        QueryWrapper<TeachPaper> queryWrapper=new QueryWrapper<>();
        if(!"admin".equals(user.getCode())){
            queryWrapper.eq("user_id", user.getId());
        }
        queryWrapper.like(StringUtils.isNotBlank(queryParam.getName()), "name", queryParam.getName());
        if(queryParam.getPunishStart() != null && queryParam.getPunishEnd() != null){
            LocalDateTime punishStart = queryParam.getPunishStart();
            String start = DateTimeFormatter.ofPattern("yyyy-MM-dd 00:00:00").format(punishStart);
            LocalDateTime punishEnd = queryParam.getPunishEnd();
            String end = DateTimeFormatter.ofPattern("yyyy-MM-dd 23:59:59").format(punishEnd);
            queryWrapper.between("punish_time", start, end);
        }
        queryWrapper.orderBy(true,pageDTO.getIsAsc().equals("asc"), ToolsUtils.camelToUnderline(pageDTO.getOrderByColumn()));
        IPage<TeachPaper> indexPage = new Page<>(pageDTO.getPageNum(),pageDTO.getPageSize());
        IPage<TeachPaper> listPage = papeInfoService.page(indexPage, queryWrapper);
        log.debug("获取的列表："+listPage);
        //获取分页信息
        Map pageInfo = ToolsUtils.wrapperPageInfo(listPage);
        return ResultUtil.successData(pageInfo);
    }

    /**
     * 添加
     * @param paperInfo
     * @return
     */
    @ApiOperation(value = "添加")
    @RequestMapping(value = "add",method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean add(TeachPaper paperInfo, HttpSession session){
        log.debug("add:"+paperInfo);
        if(paperInfo == null){
            return  ResultUtil.error(CommonEnum.BAD_PARAM);
        }
        SysUser user = (SysUser) session.getAttribute("user");
        if(null == user){
            return ResultUtil.error(CommonEnum.RELOGIN);
        }
        paperInfo.setUserId(user.getId());
        paperInfo.setState(CheckStatusEnum.NO_COMMIT.getCode());
        papeInfoService.save(paperInfo);
        log.debug("添加结果："+paperInfo);
//        //保存文件并更新saveName到user.field1
//        if (file != null && !file.isEmpty()) {
//            SysFile sysFile = new SysFile();
//            sysFile.setObjectId(teacherInfo.getId());
//            sysFile.setCategoryCode(ComCodeEnum.category_code_user);
//            SysFile saveFile=fileService.saveOrUpdateFile(sysFile,file);
//            if(saveFile!=null&&!StringUtils.isEmpty(saveFile.getSaveName())){
//                teacherInfo.setImage(saveFile.getSaveName());
//            }
//            userService.updateById(user);
//        }
        return  ResultUtil.successData(paperInfo);
    }

    /**
     * 修改
     * @param paperInfo
     * @return
     */
    @ApiOperation(value = "修改")
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean<TeachPaper> updateById(MultipartFile file, TeachPaper paperInfo, HttpSession session) {
        if (paperInfo == null) {
            return ResultUtil.error(CommonEnum.BAD_PARAM);
        }

        if (file!=null&&!file.isEmpty()) {
            SysFile sysFile=new SysFile();
            sysFile.setObjectId(paperInfo.getId());
            sysFile.setCategoryCode(ComCodeEnum.category_code_user);
            SysFile saveFile=fileService.saveOrUpdateFile(sysFile,file);
            if(saveFile!=null&&!StringUtils.isEmpty(saveFile.getSaveName())){
                paperInfo.setFileInfo(saveFile.getSaveName());
            }
        }
        paperInfo.setState(CheckStatusEnum.NO_COMMIT.getCode());

        paperInfo.setUpdateTime(LocalDateTime.now());
        papeInfoService.updateById(paperInfo);
        return ResultUtil.successData(papeInfoService.getById(paperInfo.getId())) ;
    }

    /**
     * 删除
     * @param idList
     * @return
     */
    @ApiOperation(value = "删除")
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean delete(@RequestParam("idList") List<Long> idList){
        if(idList==null||idList.isEmpty()){
            return ResultUtil.error("ID不合法！");
        }
        idList.forEach(e->papeInfoService.removeById(e));
        return ResultUtil.success();
    }

    /**
     * 提交审核
     * @param id
     * @param state
     * @return
     */
    @ApiOperation(value = "提交审核")
    @RequestMapping(value = "submitCheck",method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean submitCheck(Long id,int state, String replyInfo){
        TeachPaper teacherInfo = papeInfoService.getById(id);
        teacherInfo.setState(state);
        teacherInfo.setReplyInfo(replyInfo);
        papeInfoService.updateById(teacherInfo);
        return ResultUtil.success();
    }


}
